#include "store.h"
#include "model.h"
#include <iostream>
#include <sstream>

namespace nanok {

Store::Store(const std::string& data_dir) {
    leveldb::Options options;
    options.create_if_missing = true;
    leveldb::Status status = leveldb::DB::Open(options, data_dir, &db_);
    if (!status.ok()) {
        std::cerr << "Unable to open leveldb: " << status.ToString() << std::endl;
        exit(1);
    }
}

Store::~Store() {
    delete db_;
}

bool Store::Create(const std::string& key, const std::string& value) {
    leveldb::Status status = db_->Put(leveldb::WriteOptions(), key, value);
    return status.ok();
}

bool Store::Get(const std::string& key, std::string* value) {
    leveldb::Status status = db_->Get(leveldb::ReadOptions(), key, value);
    return status.ok();
}

bool Store::Update(const std::string& key, const std::string& value) {
    return Create(key, value);
}

bool Store::Delete(const std::string& key) {
    leveldb::Status status = db_->Delete(leveldb::WriteOptions(), key);
    return status.ok();
}

std::vector<std::string> Store::List(const std::string& prefix) {
    std::vector<std::string> results;
    leveldb::Iterator* it = db_->NewIterator(leveldb::ReadOptions());
    
    for (it->Seek(prefix); it->Valid() && it->key().starts_with(prefix); it->Next()) {
        results.push_back(it->value().ToString());
    }
    
    delete it;
    return results;
}

} // namespace nano8